package pe.edu.claretiano.admisionmatricula.util;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.primefaces.context.RequestContext;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

import java.text.ParseException;

public class Utilitario {

	public static void showFacesMessage(String texto, int tipo) {
		switch (tipo) {
		case 1:
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR, texto,
							"Error"));
			break;
		case 2:
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_FATAL, texto,
							"Fatal"));
			break;
		case 3:
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_INFO, texto,
							"Informacion"));
			break;
		case 4:
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_WARN, texto,
							"Advertencia"));
			break;
		default:
			break;
		}
	}

	public static void setearParametro(String nombre, Object valor) {
		RequestContext context = RequestContext.getCurrentInstance();
		context.addCallbackParam(nombre, valor);
	}

	static public Date deStringaDate(String sfecha) {
		Date resultado = new Date();
		try {

			SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
			resultado = sdf.parse(sfecha);
		} catch (ParseException e) {

			e.printStackTrace();
		}
		return resultado;

	}

	static public String deDateaString(Date fecha) {
		String resultado = null;

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		resultado = sdf.format(fecha);

		return resultado;
	}

	public static Date fechaActual() {
		Date fecAct = new Date();
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
			fecAct = sdf.parse(sdf.format(fecAct));
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return fecAct;

	}

	public static void mostrarReporte(Map parameters, String reporte, List lista)
			throws JRException, IOException {

		ServletContext servletContext = (ServletContext) FacesContext
				.getCurrentInstance().getExternalContext().getContext();

		String ruta = "/reportes/" + reporte;
		InputStream jasperTemplate = FacesContext.getCurrentInstance()
				.getExternalContext().getResourceAsStream(ruta);
		JasperReport jasperReport = JasperCompileManager
				.compileReport(jasperTemplate);

		JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(lista);
		JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport,
				parameters, ds);
		HttpServletResponse response = (HttpServletResponse) FacesContext
				.getCurrentInstance().getExternalContext().getResponse();
		ServletOutputStream outputStream = response.getOutputStream();
		JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
		outputStream.close();
		FacesContext.getCurrentInstance().renderResponse();
		FacesContext.getCurrentInstance().responseComplete();

	}

	public static void mostrarReporte(Map parameters, String reporte,
			List lista, String nombreReporte) throws JRException, IOException {

		byte[] bytes = null;

		System.out.println(" 1 ======>" + reporte);
		ServletContext servletContext = (ServletContext) FacesContext
				.getCurrentInstance().getExternalContext().getContext();
		System.out.println(" 2 ======>");

		System.out.println(servletContext.getRealPath("/reportes/" + reporte));
		JasperDesign jasperDesign = JRXmlLoader.load(servletContext
				.getRealPath("reportes/" + reporte));
		System.out.println(" 3 ======>");
		JasperReport jasperReport = JasperCompileManager
				.compileReport(jasperDesign);
		System.out.println(" 4 ======>");
		bytes = JasperRunManager.runReportToPdf(jasperReport, parameters,
				new JRBeanCollectionDataSource(lista));
		JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport,
				parameters, new JRBeanCollectionDataSource(lista));

		HttpServletResponse response = (HttpServletResponse) FacesContext
				.getCurrentInstance().getExternalContext().getResponse();

		response.setHeader("Content-Disposition", "inline; filename=\""
				+ nombreReporte + ".pdf\";");

		ServletOutputStream ouputStream = response.getOutputStream();

		FacesContext facesContext = FacesContext.getCurrentInstance();
		try {
			System.out.println(" 5 ======>");

			if (bytes != null && bytes.length > 0) {

				JasperExportManager.exportReportToPdfStream(jasperPrint,
						ouputStream);

				ouputStream.flush();
				ouputStream.close();

				facesContext.responseComplete();
				facesContext.renderResponse();
				System.out.println(" 6 ======>");

			}

			System.out.println(" 7 ======>");
		} catch (Exception e) {

			e.printStackTrace();
		} finally {

		}

	}

	public static void refrescarVista() {
		FacesContext context = FacesContext.getCurrentInstance();
		Application application = context.getApplication();
		ViewHandler viewHandler = application.getViewHandler();
		UIViewRoot viewRoot = viewHandler.createView(context, context
				.getViewRoot().getViewId());
		context.setViewRoot(viewRoot);
		context.renderResponse();
	}

}
